﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Money.Interfaces;
using Money.Data;
using One.Framework;

namespace Money.Services
{
    public class RefService : IRefService
    {

        Money.Data.MoneyManagerDataContext context = new MoneyManagerDataContext();

        public RefService()
        {
            context = new MoneyManagerDataContext();
        }

        public List<Ref> GetRefs()
        {
            return context.Refs.ToList<Ref>();
        }

        public Ref GetRefById(int id)
        {
            return context.Refs.SingleOrDefault<Ref>(ac => ac.RefId == id);
        }

        public void CreateRef(Ref item)
        {
            try
            {
                context.Refs.InsertOnSubmit(item);
                context.SubmitChanges();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
                throw new Exception("Cannot create ref");
            }
        }

        public void DeleteRef(int id)
        {
            try
            {
                Ref item = GetRefById(id);
                context.Refs.DeleteOnSubmit(item);
                context.SubmitChanges();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
                throw new Exception("Cannot delete ref");
            }
        }

        public void UpdateRef(Ref item)
        {
            try
            {
                context.SubmitChanges();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
                throw new Exception("Cannot update ref");
            }
        }

        public List<Ref> GetRefs(string orderBy, string orderDirection, int page, int pageSize, out int totalRecords)
        {
            try
            {
                var query = from r in context.Refs
                            select r;
                return query.OrderByPaging<Ref>(orderBy, orderDirection, page, pageSize, out totalRecords).ToList<Ref>();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
                throw new Exception("Cannot get refs");
            }
        }

        public bool CanDelete(int id)
        {
            Ref item = GetRefById(id);
            if (item != null)
            {
                if (item.Transactions.Count > 0 || item.MemorizedTransactions.Count > 0)
                    return false;
            }
            return true;
        }
    }
}
